<?php

namespace app\Modules\Admin\controllers;

use app\models\Pic;
use app\models\Product;
use app\models\User;
use Yii;
use app\models\Auction;
use app\models\AuctionSearch;
use app\models\Saleorder;
use app\models\BidRcd;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\data\ActiveDataProvider;
use yii\filters\VerbFilter;
use JpGraph\JpGraph;
/**
 * ProductController implements the CRUD actions for Product model.
 */
class AuctionController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }
    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AuctionSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Product model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $picDataProvider = new ActiveDataProvider([
            'query' => Pic::find()->where(['product_id'=>$model->product_id]),
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);
        return $this->render('view', [
            'model' => $model,
            'picDataProvider'=>$picDataProvider,
        ]);
    }

    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->pid]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionReady($product_id)
    {
        $product = Product::findOne($product_id);
        Auction::ready($product);
        return $this->redirect(['index']);
    }

    public function actionStart($id)
    {
        $model = $this->findModel($id);
        $model->start();
        return $this->redirect(['index']);
    }

    public function actionEnd($id)
    {
        $auction = $this->findModel($id);
        $auction->end();
        return $this->redirect(['index']);
    }
    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionBidRcd($id)
    {
        $model = $this->findModel($id);
        $bidRcdDataProvider = new ActiveDataProvider([
            'query' => $model->getBidRcds(),
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);
        return $this->render('bid-rcd', [
            'model' => $model,
            'bidRcdDataProvider'=>$bidRcdDataProvider,
        ]);
    }

    public function actionTest($id)
    {
        $user_ids = array_keys(User::find()->indexBy('userid')->where(['type'=>User::IS_USER])->all());

        $user = User::findOne($user_ids[array_rand($user_ids)]);
        $auction = $this->findModel($id);
        $auction->price += $auction->scope;
        $auction->actcount = $auction->product->actcount;//重置倒计时
        $auction->save(false);
        $order = Saleorder::getOrCreate($auction,$user);
        $order->num++;
        $order->save(false);
        BidRcd::create($auction,$user);
        return $this->redirect(['index']);
    }


    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Auction the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Auction::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionImg($product_id){

        $title = '最近20期成交价'; //标题

        $size = 140; //尺寸
        $width = 1200; //宽度
        $height = 400; //高度

        ob_clean();
        $auctions = Auction::find()
            ->where(['product_id'=>$product_id,'state'=>Auction::STATE_NOT_AUCTION])
            ->limit(20)
            ->all();

        $labels = [];
        $data = [];
        /** @var  $auctions Auction[]*/
        foreach($auctions as $auction){
            $labels[] = sprintf('%08d',$auction->periods);
            $data[] = $auction->price;
        }
        //编码转化
        foreach ($labels as $k => $v) {
            $labels[$k] = iconv('utf-8', 'gb2312', $v);
        }
        if(empty($data)){
            $data = [0];
            $labels = [0];
        }
        //基本配置
        JpGraph::load();
        $graph = new \Graph($width,$height,"auto");
        $graph->img->SetMargin(40,40,40,40);
        $graph->img->SetAntiAliasing();
        $graph->SetScale("textlin");
        $graph->SetShadow();
        $graph->title->Set(iconv('utf-8', 'gb2312',"{$title}"));
        $graph->title->SetFont(FF_SIMSUN,FS_NORMAL,14);
        $graph->SetFrame(false,'#ffffff',0);//去掉周围的边框
        $graph->xaxis->SetFont(FF_SIMSUN,FS_NORMAL,9);
        $graph->xaxis->SetTickLabels($labels);
        $graph->xaxis->SetLabelAngle(45);
        $graph->subtitle->SetFont(FF_SIMSUN);
        $graph->subsubtitle->SetFont(FF_SIMSUN);
        $graph->Add($this->getLine($data,'成交价','#d9534f'));
        $graph->Stroke();
    }

    protected function getLine($data,$title,$color){
        JpGraph::module('line');
        $p = new \LinePlot($data);
        $p->SetLegend(iconv('UTF-8', "GB2312//IGNORE",$title));
        $p->SetCenter();
        $p->mark->SetType(MARK_FILLEDCIRCLE);
        $p->mark->SetFillColor($color);
        $p->mark->SetColor($color);
        $p->mark->SetWidth(4);
        return $p;
    }
}